# -*- coding:utf8 -*-
from django.db import Error

__author__ = 'Forcs'

import json
import wancake.models.action.models as ac_models

from wancake.models.base.models import StbUser
from wanbatvcom.session import create_session_with_key
from wanbatvcom.utils.const_classes import ConstClass

import datetime

class ActionType(ConstClass):

    PAGE = "page"
    EVENT = "event"
    CONTENT = "content"


class ActionHandler(object):

    def __init__(self, model_name):
        action_models = __import__('wancake.models.action.models', {}, {}, ['models'])
        if hasattr(action_models, model_name):
            self.action_model_class = getattr(action_models, model_name)

    def handle_action(self, request):
        res = False
        try:
            model = self.action_model_class()
            self.on_handle_action(model, *self.handle_stb_user_info(request))
            model.save()
            res = True
        except Error, e:
            pass

        return res

    def handle_stb_user_info(self, request):
        query = request.POST

        user_id = query["userid"]
        stb_sn = query["stbsn"]
        stb_id = query["stbid"]
        stb_name = query["stbname"]
        flavor = query["flavor"]
        platform = int(query["platform"])
        time = long(query["time"]) / 1000

        stb_user, is_created = StbUser.objects.update_or_create(user_id=user_id, stb_id=stb_id, flavor=flavor)
        if is_created:
            stb_user.stb_sn = stb_sn
            stb_user.stb_name = stb_name
            stb_user.platform = platform
            stb_user.datetime_added = datetime.datetime.fromtimestamp(time)

        stb_user.datetime_last = datetime.datetime.fromtimestamp(time)
        stb_user.save()
        stb_user_id = stb_user.id
        return stb_user_id, request

    def on_handle_action(self, model,  *args):
        model.stb_user_id = args[0]

        request = args[1]
        query = request.POST
        model.flavor = query["flavor"]
        model.platform = int(query["platform"])
        model.action_code = query["actioncode"]
        time = long(query["time"]) / 1000
        model.action_time = datetime.datetime.fromtimestamp(time)
        appkey = query["appkey"]
        model.appkey = appkey
        if "session" not in query.keys():
            model.session = create_session_with_key("{}{:x}".format(appkey, time))
        else:
            model.session = request["session"]


class PageActionHandler(ActionHandler):

    def __init__(self):
        ActionHandler.__init__(self, ac_models.ActionPageRecord.__name__)

    def on_handle_action(self, model, *args):
        super(PageActionHandler, self).on_handle_action(model, *args)
        request = args[1]
        query = request.POST
        model.page_code = query["pagecode"]
        model.page_name = query["pagename"]


class EventActionHandler(ActionHandler):

    def __init__(self):
        ActionHandler.__init__(self, ac_models.ActionEventsRecord.__name__)

    def on_handle_action(self, model, *args):
        super(EventActionHandler, self).on_handle_action(model, *args)
        request = args[1]
        query = request.POST
        model.event_name = query["eventname"]
        if "eventdata" in query.keys():
            event_data_str = query["eventdata"]
            model.event_data = json.dumps(event_data_str)


class ContentActionHandler(ActionHandler):

    def __init__(self):
        ActionHandler.__init__(self, ac_models.ActionContentRecord.__name__)

    def on_handle_action(self, model, *args):
        super(ContentActionHandler, self).on_handle_action(model, *args)
        request = args[1]
        query = request.POST
        model.category_code = query["catecode"]
        model.category_name = query["catename"]
        model.content_code = query["contentcode"]
        model.content_name = query["contentname"]

ACTION_HANDLER = {
    ActionType.PAGE: PageActionHandler,
    ActionType.EVENT: EventActionHandler,
    ActionType.CONTENT: ContentActionHandler
}
